package com.jt.www.job.woxuebao;

import com.jt.www.admin.order_wxb.service.BatchInsService;
import com.jt.www.dao.mapper.woxuebao.InsBatchEntityMapper;
import com.jt.www.domain.enums.common.IsOrNotEnum;
import com.jt.www.enums.woxuebao.HandlerStatusEnum;
import com.jt.www.model.woxuebao.InsBatchEntity;
import com.jt.www.util.RedisUtil;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.Trigger;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.weekend.Weekend;
import tk.mybatis.mapper.weekend.WeekendCriteria;

import java.util.List;

/**
 * 我学保批量投保
 *
 * @author shaoyunan
 * @date 2020-09-18
 */
@Component
@EnableScheduling
public class CheckBatchInsSubmitTask implements SchedulingConfigurer {

    public static final Logger log = LoggerFactory.getLogger(CheckBatchInsSubmitTask.class);
    /**
     * 单个服务器出单查询缓存失效时间 因不同的定时任务决定
     */
    private static final long IME_OUT = 300L;
    /**
     * 我学保批量投保
     */
    private static final String BATCH_INS_LOCK_KEY = "EDU_BATCH_INS";
    @Autowired
    InsBatchEntityMapper insBatchEntityMapper;
    @Autowired
    BatchInsService batchInsService;
    /**
     * 任务开关
     */
    @Value("${jtpf.batchins.submit.open}")
    private int checkOpen;
    /**
     * 任务执行周期
     */
    @Value("${jtpf.batchins.submit.cron}")
    private String cron;

    @Override
    public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
        if (checkOpen != 1) {
            return;
        }
        Runnable task0 = () -> checkStart();
        Trigger trigger0 = triggerContext -> new CronTrigger(cron).nextExecutionTime(triggerContext);
        taskRegistrar.addTriggerTask(task0, trigger0);
    }

    private void checkStart() {
        //多个服务同时启动定时任务，在执行体开始时判断是否有其他线程在执行
        //设置缓存失败表示有在执行的任务
        if (!RedisUtil.setLock(IME_OUT, BATCH_INS_LOCK_KEY)) {
            return;
        }
        try {
            log.info("我学保批量投保(投保下发)开始!");
            Weekend<InsBatchEntity> weekend = Weekend.of(InsBatchEntity.class);
            WeekendCriteria<InsBatchEntity, Object> criteria = weekend.weekendCriteria();
            criteria.andEqualTo(InsBatchEntity::getHandleStatus, HandlerStatusEnum.NO_INS.getCode());
            criteria.andEqualTo(InsBatchEntity::getIsDeleted, IsOrNotEnum.NO.getValue());
            //重试5次
            criteria.andLessThan(InsBatchEntity::getTimes, 6);
            //从第0位开始查询，查询出前300个
            RowBounds rowBounds = new RowBounds(0, 300);
            List<InsBatchEntity> resultList = insBatchEntityMapper.selectByExampleAndRowBounds(weekend, rowBounds);
            if (!CollectionUtils.isEmpty(resultList)) {
                batchInsService.sendMessageToIns(resultList);
            }
        } catch (Exception e) {
            log.info("我学保批量投保(投保下发)出错!");
        } finally {
            //删除缓存
            RedisUtil.delete(BATCH_INS_LOCK_KEY);
            log.info("我学保批量投保(投保下发)结束!");
        }
    }

}
